<template>
  <div class="app-container">
    <!-- 左侧树形菜单 -->
    <div class="tree-panel">
      <div class="head-container">
        <el-input
          v-model="projectName"
          placeholder="请输入培训项目"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
          @keyup.enter.native="filterTree"
        />
      </div>
      <el-tree
        ref="tree"
        :data="projectOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        node-key="id"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
      />
    </div>

    <el-col :span="20" style="padding: 20px">
      <!-- 搜索区域 -->
      <el-form
        :model="queryParams"
        inline
        size="small"
        v-show="showSearch"
        label-width="100px"
      >
        <el-row :gutter="20">
          <!-- 姓名 -->
          <el-col :span="6">
            <el-form-item label="姓名">
              <el-input
                v-model="queryParams.studentName"
                placeholder="请输入姓名"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 手机号码 -->
          <el-col :span="6">
            <el-form-item label="手机号码">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 证件编号 -->
          <el-col :span="6">
            <el-form-item label="证件编号">
              <el-input
                v-model="queryParams.idNumber"
                placeholder="请输入证件编号"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 证书编号 -->
          <el-col :span="6">
            <el-form-item label="证书编号">
              <el-input
                v-model="queryParams.certificateNo"
                placeholder="请输入证书编号"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 单位名称 -->
          <el-col :span="6">
            <el-form-item label="单位名称">
              <el-input
                v-model="queryParams.unitName"
                placeholder="请输入单位名称"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 发放时间 -->
          <el-col :span="6">
            <el-form-item label="发放时间">
              <el-date-picker
                v-model="queryParams.issueTimeRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 210px"
              />
            </el-form-item>
          </el-col>

          <!-- 有效期起 -->
          <el-col :span="6">
            <el-form-item label="有效期起">
              <el-date-picker
                v-model="queryParams.validityStartDate"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 210px"
              />
            </el-form-item>
          </el-col>

          <!-- 有效期止 -->
          <el-col :span="6">
            <el-form-item label="有效期止">
              <el-date-picker
                v-model="queryParams.validityEndDate"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 210px"
              />
            </el-form-item>
          </el-col>

          <!-- 电子证书状态 -->
          <el-col :span="6">
            <el-form-item label="电子证书">
              <el-select
                v-model="queryParams.digitalStatus"
                placeholder="选择电子证书状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.digital_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 纸质证书状态 -->
          <el-col :span="6">
            <el-form-item label="纸质证书">
              <el-select
                v-model="queryParams.paperStatus"
                placeholder="选择纸质证书状态"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.paper_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 备注 -->
          <el-col :span="6">
            <el-form-item label="备注">
              <el-input
                v-model="queryParams.remark"
                placeholder="请输入备注"
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <!-- 操作按钮 -->
          <el-col :span="6">
            <el-form-item style="float: right; margin-right: 50px">
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-col>

          <!-- 纸质证书领取方式 -->
          <el-col :span="12">
            <el-form-item label-width="150px" label="纸质证书领取方式">
              <el-select
                v-model="queryParams.receiveMethod"
                placeholder="选择纸质证书领取方式"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.receive_method"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 临近过期 -->
          <el-col :span="12">
            <el-form-item label="临近过期">
              <el-select
                v-model="queryParams.expireReminderDays"
                placeholder="选择临近过期期限"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.expire_reminder_days"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <!-- 按钮组 -->
        <el-col :span="24">
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 10px 0;
            "
          >
            <!-- 左侧按钮 -->
            <div style="display: flex">
              <span class="group-label">管理列表</span>
              <el-button size="medium" @click="handleExport">导出</el-button>
              <el-button size="medium" @click="handleRemark">备注</el-button>
              <el-button size="medium" @click="notifyStudent" :disabled="ids.length ===0"
                >通知学员</el-button
              >
            </div>

            <!-- 右侧按钮 -->
            <div style="display: flex; gap: 10px">
              <column-config-dialog-vue
                :showSearch.sync="showSearch"
                :columns="tableColumns"
                @queryTable="getList"
              ></column-config-dialog-vue>
            </div>
          </div>
        </el-col>

        <!-- 第二行：电子证书按钮 -->
        <el-col :span="16">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">电子证书</span>
            <el-button size="medium" @click="generateElectronicCertificate"
              >生成电子证书</el-button
            >
            <el-button size="medium" @click="revokeElectronicCertificate"
              >撤销电子证书</el-button
            >
            <el-button size="medium" @click="viewElectronicCertificate"
              >查看电子证书</el-button
            >
            <el-button size="medium" @click="downloadElectronicCertificate"
              >下载电子证书</el-button
            >
            <el-button size="medium" @click="sendElectronicCertificate"
              >发送电子证书</el-button
            >
          </div>
        </el-col>
        <el-col :span="8">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">复训换证</span>
            <el-button size="medium" @click="handleRenewalApply"
              >报名复训换证</el-button
            >
          </div>
        </el-col>

        <!-- 第三行：纸质证书按钮 -->
        <el-col :span="12">
          <div style="display: flex; padding: 10px 0; float: left">
            <span class="group-label">纸质证书</span>
            <el-button size="medium" @click="fastIssuePaperCertificate"
              >快递发放证书</el-button
            >
            <el-button size="medium" @click="onSitePickupCertificate"
              >现场领取证书</el-button
            >
          </div>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="certificateIssueList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />

        <!-- 证书类型 -->
        <el-table-column
          label="证书类型"
          align="center"
          prop="certificateType"
          v-if="
            tableColumns.find((col) => col.prop === 'certificateType').visible
          "
        >
          <template slot-scope="scope">
            {{
              dict.label.certificate_type[scope.row.certificateType] ||
              scope.row.certificateType
            }}
          </template>
        </el-table-column>

        <!-- 电子证书状态 -->
        <el-table-column
          label="电子证书状态"
          align="center"
          prop="digitalStatus"
          v-if="
            tableColumns.find((col) => col.prop === 'digitalStatus').visible
          "
        >
          <template slot-scope="scope">
            {{
              dict.label.digital_status[scope.row.digitalStatus] ||
              scope.row.digitalStatus
            }}
          </template>
        </el-table-column>

        <!-- 纸质证书状态 -->
        <el-table-column
          label="纸质证书状态"
          align="center"
          prop="paperStatus"
          v-if="tableColumns.find((col) => col.prop === 'paperStatus').visible"
        >
          <template slot-scope="scope">
            {{
              dict.label.paper_status[scope.row.paperStatus] ||
              scope.row.paperStatus
            }}
          </template>
        </el-table-column>

        <!-- 证书编号 -->
        <el-table-column
          label="证书编号"
          align="center"
          prop="certificateNo"
          v-if="
            tableColumns.find((col) => col.prop === 'certificateNo').visible
          "
        />

        <!-- 证件编号 -->
        <el-table-column
          label="证件编号"
          align="center"
          prop="idNumber"
          v-if="tableColumns.find((col) => col.prop === 'idNumber').visible"
        />

        <!-- 姓名 -->
        <el-table-column
          label="姓名"
          align="center"
          prop="studentName"
          v-if="tableColumns.find((col) => col.prop === 'studentName').visible"
        />

        <!-- 证件编号 -->
        <el-table-column
          label="证件编号"
          align="center"
          prop="documentNo"
          v-if="tableColumns.find((col) => col.prop === 'documentNo').visible"
        />

        <!-- 性别 -->
        <el-table-column
          label="性别"
          align="center"
          prop="sex"
          v-if="tableColumns.find((col) => col.prop === 'sex').visible"
        />

        <!-- 电话 -->
        <el-table-column
          label="电话"
          align="center"
          prop="phonenumber"
          v-if="tableColumns.find((col) => col.prop === 'phonenumber').visible"
        />

        <!-- 单位名称 -->
        <el-table-column
          label="单位名称"
          align="center"
          prop="unitName"
          v-if="tableColumns.find((col) => col.prop === 'unitName').visible"
        />

        <!-- 培训项目 -->
        <el-table-column
          label="培训项目"
          align="center"
          prop="projectName"
          v-if="tableColumns.find((col) => col.prop === 'projectName').visible"
        />

        <!-- 证书发放时间 -->
        <el-table-column
          label="证书发放时间"
          align="center"
          prop="issueTime"
          v-if="tableColumns.find((col) => col.prop === 'issueTime').visible"
        >
          <template slot-scope="scope">
            {{ scope.row.issueTime }}
          </template>
        </el-table-column>

        <!-- 证书有效期起 -->
        <el-table-column
          label="证书有效期起"
          align="center"
          prop="validityStart"
          v-if="
            tableColumns.find((col) => col.prop === 'validityStart').visible
          "
        />

        <!-- 证书有效期止 -->
        <el-table-column
          label="证书有效期止"
          align="center"
          prop="validityEnd"
          v-if="tableColumns.find((col) => col.prop === 'validityEnd').visible"
        />

        <!-- 纸质证书发放时间 -->
        <el-table-column
          label="纸质证书发放时间"
          align="center"
          prop="paperIssueTime"
          v-if="
            tableColumns.find((col) => col.prop === 'paperIssueTime').visible
          "
        />

        <!-- 纸质证书领取方式 -->
        <el-table-column
          label="纸质证书领取方式"
          align="center"
          prop="receiveMethod"
          v-if="
            tableColumns.find((col) => col.prop === 'receiveMethod').visible
          "
        >
          <template slot-scope="scope">
            {{
              dict.label.receive_method[scope.row.receiveMethod] ||
              scope.row.receiveMethod
            }}
          </template>
        </el-table-column>

        <!-- 快递单号 -->
        <el-table-column
          label="快递单号"
          align="center"
          prop="trackingNo"
          v-if="tableColumns.find((col) => col.prop === 'trackingNo').visible"
        />

        <!-- 备注 -->
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          v-if="tableColumns.find((col) => col.prop === 'remark').visible"
        />

        <!-- 操作 -->
        <el-table-column
          label="操作"
          width="280px"
          align="center"
          class-name="small-padding fixed-width"
          v-if="tableColumns.find((col) => col.prop === 'operation').visible"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleRemarkRow(scope.row)"
              >备注</el-button
            >
            <el-button size="mini" type="text" @click="notifyStudent(scope.row)"
              >学员通知</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="downloadElectronicCertificate"
              >下载证书</el-button
            >
            <!-- <el-button size="mini" type="text" @click="printCertificate"
              >打印证书</el-button
            > -->
            <el-button size="mini" type="text" @click="copyOrder(scope.row)"
              >复制单号</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改题组管理对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="800px"
        custom-class="dialog-custom"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <!-- 第一行：题组名称 和 题组题型 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="题组名称" prop="groupName">
                <el-input
                  v-model="form.groupName"
                  placeholder="请输入题组名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="题组题型" prop="groupType">
                <el-select
                  v-model="form.groupType"
                  placeholder="请选择题组题型"
                >
                  <el-option
                    v-for="dict in dict.type.question_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第二行：项目类别 -->
          <el-form-item label="项目类别" prop="trainingProjectId">
            <el-cascader
              v-model="form.trainingProjectId"
              :options="projectOptions"
              :props="{
                checkStrictly: true,
                emitPath: false, //只传入子节点的id
                value: 'id',
                label: 'label',
                children: 'children',
              }"
              placeholder="请选择项目类别"
              clearable
            />
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </el-dialog>

      <!-- 备注 -->
      <RemarkDialogVue
        :visible.sync="remarkDialogVisible"
        :record-id="currentRecordId"
        :remark-history="remarkList"
        :remark-type="'9'"
        @success="refreshRemarkList"
      />
      <!-- 新增个人复审资料 -->
      <add-personal-review
        ref="addPersonalReview"
        :dict-data="dictData"
      ></add-personal-review>
      <!-- 生成电子证书 -->
      <GenerateElectronicCertificateDialogVue
        :visible.sync="generateDialogVisible"
        :certificate-data="selectedCertificates"
        :template-list="templateList"
        @submit="handleGenerateSubmit"
      />
      <!-- 撤销电子证书 -->
      <RevokeElectronicCertificateDialog
        :visible.sync="revokeElectronicVisible"
        :certificate-data="selectedCertificates"
        :template-list="templateList"
        @submit="handleRevokeSubmit"
      />
      <!-- 查看电子证书 -->
      <ViewCertificateDialogVue
        :visible.sync="viewCertificateTemplateDialog"
        :template-data="viewCertificateTemplateData"
      />
      <!-- 快递发放证书 -->
      <FastIssuePaperCertificateDialog
        :visible.sync="fastIssueVisible"
        :certificate-data="FastIssueData"
        @submit="handleFastIssueSubmit"
      />
      <!-- 现场领取证书 -->
      <OnSitePickupDialog
        :visible.sync="onSitePickupVisible"
        :certificate-list="selectedCertificatesForPickup"
        @confirm="handleConfirmPickup"
      />
      <!-- 学员通知弹窗 -->
      <student-notice-dialog
        :visible.sync="noticeDialogVisible"
        :class-id="currentClassId"
        @notice-sent="handleNoticeSent"
      />
    </el-col>
  </div>
</template>

<script>
import {
  listCertificateIssue,
  getCertificateIssue,
  delCertificateIssue,
  addCertificateIssue,
  updateCertificateIssue,
  getElectronicInfo,
  expressPaperCertificate,
  getCertificateIssueList,
  scenePaperCertificate,
  generateElectronic,
  cancelElectronic,
} from "@/api/certificate/issue";
import { listCertificateTemplate } from "@/api/certificate/certificateTemplate";
import { listRemarksByParams } from "@/api/training/remarks";
import { projectTreeSelect } from "@/api/training/projects";
import { getDicts } from "@/api/system/dict/data";
import ColumnConfigDialogVue from "../../../components/ColumnConfig/ColumnConfigDialog.vue";
// 备注
import RemarkDialogVue from "../../../components/Certificate/template/RemarkDialog.vue";
// 新增个人复审资料
import AddPersonalReview from "@/components/Certificate/reexamination/AddPersonalReview.vue";
// 生成电子证书
import GenerateElectronicCertificateDialogVue from "../../../components/Certificate/issue/GenerateElectronicCertificateDialog.vue";
// 撤销电子证书
import RevokeElectronicCertificateDialog from "../../../components/Certificate/issue/RevokeElectronicCertificateDialog.vue";
// 查看电子证书
import ViewCertificateDialogVue from "../../../components/Certificate/issue/ViewCertificateDialog.vue";
// 快递发放证书
import FastIssuePaperCertificateDialog from "../../../components/Certificate/issue/FastIssuePaperCertificateDialog.vue";
// 现场领取证书
import OnSitePickupDialog from "../../../components/Certificate/issue/OnSitePickupDialog.vue";
// 导入工具类
import CertificateDownloader from "../../../components/Certificate/issue/certificateDownloader";
import studentNoticeDialog from "@/components/class/studentNoticeDialog.vue";
export default {
  name: "CertificateIssue",
  dicts: [
    "certificate_type",
    "digital_status",
    "paper_status",
    "receive_method",
    "expire_reminder_days",
  ],
  components: {
    ColumnConfigDialogVue,
    RemarkDialogVue,
    GenerateElectronicCertificateDialogVue,
    ViewCertificateDialogVue,
    FastIssuePaperCertificateDialog,
    OnSitePickupDialog,
    RevokeElectronicCertificateDialog,
    AddPersonalReview,
    studentNoticeDialog
  },
  data() {
    return {
      currentClassId: '',
      noticeDialogVisible: false,

      registrationId:"",
      registrationIds:[],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 证书发放管理表格数据
      certificateIssueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateType: null,
        digitalStatus: null,
        paperStatus: null,
        certificateNo: null,
        digitalIssueTime: null,

        paperIssueTime: null,
        receiveMethod: null,
        trackingNo: null,
        immediatePublish: null,
        revokeReason: null,
        expireReminderDays: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //新增数据定义
      //树形结构数据
      // 所有部门树选项
      projectName: "",
      projectOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 缓存字典数据
      dictCache: {
        certificate_type: {},
        digital_status: {},
        paper_status: {},
        receive_method: {},
      },
      // 添加字典数据存储
      dictData: {
        unitNatureOptions: [],
        documentTypeOptions: [],
        nationOptions: [],
        educationOptions: [],
        administrativeAreaOptions: [],
        userTypeOptions: [],
      },
      // 列显隐
      tableColumns: [
        { prop: "certificateType", label: "证书类型", visible: true },
        { prop: "digitalStatus", label: "电子证书状态", visible: true },
        { prop: "paperStatus", label: "纸质证书状态", visible: true },
        { prop: "certificateNo", label: "证书编号", visible: true },
        { prop: "idNumber", label: "编号", visible: true },
        { prop: "studentName", label: "姓名", visible: true },
        { prop: "documentNo", label: "证件编号", visible: true },
        { prop: "sex", label: "性别", visible: true },
        { prop: "phonenumber", label: "电话", visible: true },
        { prop: "unitName", label: "单位名称", visible: true },
        { prop: "projectName", label: "培训项目", visible: true },
        { prop: "issueTime", label: "证书发放时间", visible: true },
        { prop: "validityStart", label: "证书有效期起", visible: true },
        { prop: "validityEnd", label: "证书有效期止", visible: true },
        { prop: "paperIssueTime", label: "纸质证书发放时间", visible: true },
        { prop: "receiveMethod", label: "纸质证书领取方式", visible: true },
        { prop: "trackingNo", label: "快递单号", visible: true },
        { prop: "remark", label: "备注", visible: true },
        { prop: "operation", label: "操作", visible: true },
      ],
      //备注
      remarkDialogVisible: false,
      currentRecordId: "",
      remarkList: [], // 存储备注历史
      // 生成电子证书
      generateDialogVisible: false,
      selectedCertificates: [],
      //撤销电子证书
      revokeElectronicVisible: false,
      //模板下拉列表
      templateList: [],
      //查看电子证书
      viewCertificateTemplateDialog: false,
      viewCertificateTemplateData: [],
      //快递发放证书
      fastIssueVisible: false,
      tempIssueData: [], //多选数据
      FastIssueData: [],
      // 现场领取证书
      onSitePickupVisible: false,
      selectedCertificatesForPickup: [], // 存储选中的证书数据
    };
  },
  created() {
    this.getList();
    this.getProjectTree();
    this.$nextTick(async () => {
      await this.loadDicts();
    });
    this.loadAllDicts();
  },
  filters: {
    formatDate(value) {
      if (value) {
        return moment(value).format("YYYY-MM-DD HH:mm:ss");
      }
      return "";
    },
  },
  methods: {
    async loadDicts() {
      this.dictCache.certificate_type = this.dict.label.certificate_type;
      this.dictCache.digital_status = this.dict.label.digital_status;
      this.dictCache.paper_status = this.dict.label.paper_status;
      this.dictCache.receive_method = this.dict.label.receive_method;
    },
    // 统一加载所有字典数据
    loadAllDicts() {
      const dictPromises = [
        getDicts("unit_nature"),
        getDicts("pxzx_zjlx"),
        getDicts("pub_mz"),
        getDicts("pxzx_xl"),
        getDicts("administrative_area"),
        getDicts("rylx"),
      ];

      Promise.all(dictPromises)
        .then((responses) => {
          this.dictData.unitNatureOptions = responses[0].data;
          this.dictData.documentTypeOptions = responses[1].data;
          this.dictData.nationOptions = responses[2].data;
          this.dictData.educationOptions = responses[3].data;
          this.dictData.administrativeAreaOptions = responses[4].data;
          this.dictData.userTypeOptions = responses[5].data;
          console.log("字典数据加载成功:", responses);
          console.log("字典数据:", this.dictData);
        })
        .catch((error) => {
          console.error("字典数据加载失败:", error);
        });
    },
    /** 查询题组管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.certificateType = "1";
      getCertificateIssueList(this.queryParams).then((response) => {
        this.certificateIssueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        certificateIssueId: null,
        templateId: null,
        studentId: null,
        projectId: null,
        registrationId: null,
        certificateType: null,
        digitalStatus: null,
        paperStatus: null,
        certificateNo: null,
        digitalIssueTime: null,
        validityStartDate: null,
        validityEndDate: null,
        paperIssueTime: null,
        receiveMethod: null,
        trackingNo: null,
        immediatePublish: null,
        revokeReason: null,
        expireReminderDays: null,
        createdBy: null,
        updatedBy: null,
        createdTime: null,
        updatedTime: null,
        remark: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 将时间范围拆分为 start 和 end
      if (this.queryParams.issueTimeRange) {
        this.queryParams.digitalIssueStartTime =
          this.queryParams.issueTimeRange[0];
        this.queryParams.digitalIssueEndTime =
          this.queryParams.issueTimeRange[1];
      }
      if (this.queryParams.validityStartDate) {
        this.queryParams.validityStartStartTime =
          this.queryParams.validityStartDate[0];
        this.queryParams.validityStartEndTime =
          this.queryParams.validityStartDate[1];
      }
      if (this.queryParams.validityEndDate) {
        this.queryParams.validityEndStartTime =
          this.queryParams.validityEndDate[0];
        this.queryParams.validityEndEndTime =
          this.queryParams.validityEndDate[1];
      }

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.recordDto=selection
      this.registrationIds = selection.map((item) => item.registrationId);
      this.ids = selection.map((item) => item.certificateIssueId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;

      // 将选中的数据赋值给 FastIssueData
      this.tempIssueData = selection;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加证书发放管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const certificateIssueId = row.certificateIssueId || this.ids;
      getCertificateIssue(certificateIssueId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改证书发放管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.certificateIssueId != null) {
            updateCertificateIssue(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCertificateIssue(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const certificateIssueIds = row.certificateIssueId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除证书发放管理编号为"' +
            certificateIssueIds +
            '"的数据项？'
        )
        .then(function () {
          return delCertificateIssue(certificateIssueIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "training/certificateIssue/export",
        {
          ...this.queryParams,
        },
        `certificateIssue_${new Date().getTime()}.xlsx`
      );
    },

    //新增方法
    //树形结构
    filterTree() {
      this.$refs.tree.filter(this.projectName);
    },
    // 获取树形数据
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.projectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.trainingProjectId = data.id;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    flattenTree(tree) {
      let result = [];
      tree.forEach((node) => {
        result.push({ id: node.id, label: node.label });
        if (node.children && node.children.length > 0) {
          result = result.concat(this.flattenTree(node.children));
        }
      });
      return result;
    },
    // 切换搜索显示
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    // 刷新表格数据
    refreshTable() {
      this.getList();
    },
    // 切换排序列显示
    toggleSort() {
      // 根据实际需求实现排序列的显示/隐藏逻辑
      this.$message.info("排序列功能待实现");
    },

    //证书

    // // 查看证书模板
    // handleViewTemplate() {
    //   this.$message.info("查看证书模板功能待实现");
    // },
    // 删除证书模板
    handleDeleteTemplate() {
      this.$message.info("删除证书模板功能待实现");
    },
    // 备注
    handleRemark() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行备注");
        return;
      }

      const row = this.certificateIssueList.find(
        (item) => item.certificateIssueId === this.ids[0]
      );
      if (!row) return;

      this.currentRecordId = row.certificateIssueId;

      var params = { foreignId: row.certificateIssueId, remarkType: "9" };
      listRemarksByParams(params).then((res) => {
        this.remarkList = res.rows;
        this.remarkDialogVisible = true;
      });
    },
    // 查看证书
    handleViewCertificate(row) {
      this.$message.info(`查看证书：${row.certificateName}`);
    },
    // 复制
    handleCopy(row) {
      this.$message.info(`复制证书：${row.certificateName}`);
    },
    // 备注行
    handleRemarkRow(row) {
      var params = { foreignId: row.certificateIssueId, remarkType: "9" };
      listRemarksByParams(params).then((res) => {
        this.remarkList = res.rows;
        this.remarkDialogVisible = true;
      });
    },

    // 刷新备注列表
    refreshRemarkList(remark) {
      this.getRemarkHistory(this.currentRecordId);
    },

    // 通知学员
    notifyStudent(row) {
      let targetRow =null;
      // 优先获取行数据，无则取选中数据
      if(row.studentId !==undefined){
        targetRow =row
      }else{
        targetRow = this.recordDto[0];
        if (!targetRow ) return this.$message.warning('请选择一个学员');
      }
      this.currentClassId=targetRow.trainingClassId+""
      this.noticeDialogVisible =true
    },
    handleNoticeSent() {
      // 通知发送后处理
      this.noticeDialogVisible=false
      this.getList();
    },
    // 生成电子证书
    generateElectronicCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      // 获取选中的证书数据
      this.selectedCertificates = this.certificateIssueList.filter((item) =>
        this.ids.includes(item.certificateIssueId)
      );

      //模板列表数据
      listCertificateTemplate().then((res) => {
        console.log("模板列表数据：", res);
        this.templateList = res.rows;
        // 确保数据加载完成后再显示对话框
        this.$nextTick(() => {
          this.generateDialogVisible = true;
        });
      });
    },
    // 处理生成证书提交
    handleGenerateSubmit(data) {
      console.log("提交的数据：", data);
      generateElectronic(data)
        .then(() => {
          this.$modal.msgSuccess("电子证书生成成功");
          this.getList(); // 刷新列表
          this.generateDialogVisible = false; // 关闭对话框
        })
        .catch((err) => {
          this.$message.error("生成失败：" + err.message);
        });
    },
    //查看电子证书
    // 撤销电子证书
    revokeElectronicCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      // 获取选中的证书数据
      this.selectedCertificates = this.certificateIssueList.filter((item) =>
        this.ids.includes(item.certificateIssueId)
      );

      //模板列表数据
      listCertificateTemplate().then((res) => {
        this.templateList = res.rows;
        // 确保数据加载完成后再显示对话框
        this.$nextTick(() => {
          this.revokeElectronicVisible = true;
        });
      });
    },
    handleRevokeSubmit(data) {
      console.log("提交的数据：", data);

      cancelElectronic(data)
        .then(() => {
          this.$modal.msgSuccess("撤销电子证书成功");
          this.getList(); // 刷新列表
          this.generateDialogVisible = false; // 关闭对话框
        })
        .catch((err) => {
          this.$message.error("生成失败：" + err.message);
        });
    },
    // 查看电子证书
    viewElectronicCertificate() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行查看");
        return;
      }
      // 获取所有选中的证书数据
      // const certificateIssueIds = this.ids[0];
      const certificateIssueIds = this.ids;

      // 调用接口批量获取电子证书信息
      getElectronicInfo(certificateIssueIds)
        .then((res) => {
          const certificates = res.data || [];

          if (certificates.length === 0) {
            this.$message.warning("未获取到证书信息");
            return;
          }
          this.viewCertificateTemplateData = certificates;

          // 替换原来的打印语句
          console.log("父组件传递的数据", this.viewCertificateTemplateData);

          // 确保数据已经设置后再显示对话框
          this.$nextTick(() => {
            this.viewCertificateTemplateDialog = true;
          });
          // this.$refs.viewCertificateTemplateDialog.open(certificates);
        })
        .catch((err) => {
          this.$message.error("获取证书失败：" + err.message);
        });
    },

    // 下载电子证书
    async downloadElectronicCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      try {
        // 获取证书数据
        const certificateIssueIds = this.ids;
        const res = await getElectronicInfo(certificateIssueIds);
        const certificates = res.data || [];

        // 使用工具类下载证书
        await CertificateDownloader.downloadCertificates(certificates);

        this.$message.success("证书下载成功");
      } catch (error) {
        this.$message.error("下载失败：" + error.message);
      }
    },

    // 发送电子证书
    sendElectronicCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }
      this.$api.certificate
        .sendElectronicCertificates({ ids: this.ids })
        .then(() => {
          this.$modal.msgSuccess("电子证书已发送");
          this.getList();
        })
        .catch((err) => {
          this.$message.error("发送失败：" + err.message);
        });
    },
    // 报名复训换证
    handleRenewalApply() {
      this.$refs.addPersonalReview.open("add");
    },

    // 打印证书
    printCertificate() {
      if (this.ids.length !== 1) {
        this.$message.warning("请选择一条记录进行打印");
        return;
      }
      const id = this.ids[0];
      this.$api.certificate
        .getPrintableCertificate(id)
        .then((res) => {
          // 假设返回的是 PDF 或 HTML 内容，可以使用 window.open 或 iframe 打印
          window.open(res.data.url, "_blank");
        })
        .catch((err) => {
          this.$message.error("获取打印内容失败：" + err.message);
        });
    },
    // 复制单号
    copyOrder(row) {
      console.log("复制单号", row);
      if (!row || !row.trackingNo) {
        this.$message.warning("该记录无快递单号");
        return;
      }
      navigator.clipboard
        .writeText(row.trackingNo)
        .then(() => {
          this.$message.success("快递单号已复制到剪贴板");
        })
        .catch(() => {
          this.$message.error("复制失败");
        });
    },
    // 生成电子证书
    openGenerateDialog() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      // 获取选中的证书数据
      this.selectedCertificates = this.certificateIssueList.filter((item) =>
        this.ids.includes(item.groupId)
      );

      this.generateDialogVisible = true;
    },
    //

    // 快递发放证书
    fastIssuePaperCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      this.FastIssueData = this.tempIssueData.map((item) => ({
        certificateIssueId: item.certificateIssueId,
        certificateNo: item.certificateIssueId,
        studentName: item.studentName,
        idNumber: item.idNumber,
        phonenumber: item.phonenumber,
        trackingNo: item.trackingNo,
      }));

      this.fastIssueVisible = true;
    },
    // 快递发放证书
    handleFastIssueSubmit(data) {
      console.log(data);

      expressPaperCertificate(data)
        .then(() => {
          this.$modal.msgSuccess("证书已安排快递发放");
          this.getList(); // 刷新列表
          this.fastIssueVisible = false; // 关闭对话框
        })
        .catch((err) => {
          this.$message.error("发放失败：" + err.message);
        });
    },
    // 现场领取证书
    onSitePickupCertificate() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      this.selectedCertificatesForPickup = this.tempIssueData.map((item) => ({
        certificateIssueId: item.certificateIssueId,
        certificateNo: item.certificateIssueId,
        studentName: item.studentName,
        idNumber: item.idNumber,
        phonenumber: item.phonenumber,
        trackingNo: item.trackingNo,
      }));

      this.onSitePickupVisible = true;
    },
    // 显示现场领取弹窗
    showOnSitePickupDialog() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择学员");
        return;
      }

      // 获取选中行的数据
      this.selectedCertificatesForPickup = this.certificateIssueList.filter(
        (item) => this.ids.includes(item.groupId)
      );

      this.onSitePickupVisible = true;
    },

    // 确认现场领取
    handleConfirmPickup() {
      const ids = this.selectedCertificatesForPickup.map(
        (item) => item.certificateIssueId
      );

      scenePaperCertificate(ids)
        .then(() => {
          this.$modal.msgSuccess("证书已标记为现场领取");
          this.getList(); // 刷新列表
          this.onSitePickupVisible = false;
        })
        .catch((err) => {
          this.$message.error("标记失败：" + err.message);
        });
    },
  },
  watch: {
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
  },
};
</script>


<style scoped>
.app-container {
  display: flex;
  height: 100%;
}

.tree-panel {
  width: 360px;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  padding: 20px;
}

.head-container {
  margin-bottom: 20px;
}

.el-form {
  margin-top: 20px;
  padding: 0 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}
.dialog-custom {
  min-height: 500px !important;
  max-height: 600px !important;
  overflow-y: auto;
}

.group-label {
  color: #666;
  font-weight: 500;
  white-space: nowrap;
  font-size: 16px;
  margin: auto;
  margin-right: 5px;
  width: 100px; /* 固定宽度 */
  text-align: right; /* 右对齐 */
  display: inline-block;
  vertical-align: middle;
}

.el-button {
  width: 100px;
  height: 32px;
  line-height: 32px;
  padding: 0;
  text-align: center;
  font-size: 14px;
  margin-right: 8px;
}
</style>
